#include "search.h"
#include "ui_search.h"
#include <QUdpSocket>
#include <QHostAddress>
#include <QTimer>
#include <QDebug>
Search::Search(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Search)

{
    ui->setupUi(this);
    udpSocket = NULL;

    ui->label_2->setStyleSheet("background-color: rgba(255, 255, 255, 0);color: black;font-family: '黑体'; font-size: 18px;");
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout,this,&Search::updateTime);
    timer->start(1000);
    updateTime();

}

Search::~Search()
{
    delete ui;
}

void Search::updateTime()
{
     ui->label_2->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
}

void Search::on_pushButton_clicked()
{
//    emit searchSignal(ui->lineEdit->text());
    QByteArray datagram = "SEARCH_DEVICE";  // 搜索请求内容
    if(udpSocket == NULL)
    {
        //socket套接字
        udpSocket = new QUdpSocket(this);
        //监控套接字
        connect(udpSocket, &QUdpSocket::readyRead, this, &Search::processPendingDatagrams);
    }
    udpSocket->writeDatagram(datagram, QHostAddress("192.169.2.137"), ui->lineEdit->text().toShort());
}
void Search::processPendingDatagrams()
{
    // 处理接收到的广播数据包
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->bytesAvailable());
        QHostAddress sender;
        quint16 senderPort;
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        // 这里假设设备通过 UDP 响应一个字符串
        QString deviceInfo = QString::fromUtf8(datagram);
        qDebug() << "Received device info from" << sender.toString() << ":" << deviceInfo;

        // 显示设备信息，可以将其显示在界面上
        ui->label->setText("设备名称: " + deviceInfo + " (" + sender.toString() + ")");
    }
}
